package com.xcw.jac;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileRequestExample {
    public static void main(String[] args) throws IOException {
        String url = "http://example.com/upload";  // 文件上传的URL

        // 文件路径
        String filePath = "/path/to/file.txt";

        // 创建连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // 设置请求头
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");

        try (OutputStream outputStream = conn.getOutputStream();
             FileInputStream fileInputStream = new FileInputStream(filePath)) {

            // 写入文件数据
            outputStream.write(("*****\r\n" +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"" + new File(filePath).getName() + "\"\r\n" +
                    "Content-Type: application/octet-stream\r\n\r\n").getBytes());

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.write(("\r\n--" + "*****" + "--\r\n").getBytes());
        }

        // 获取响应
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应内容
        } else {
            // 处理错误情况
        }

        conn.disconnect();
    }
}